import Vue from 'vue'
import Vuex from 'vuex'
import { loginApi,logoutApi,getUserInfoApi,getUserRolesApi } from '@/api/auth'
import { getToken, setToken, removeToken } from '@/utils/cookie'

Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    userInfo: sessionStorage.getItem("user") ? JSON.parse(sessionStorage.getItem("user")) : null,
    webSiteInfo: {
      showList:[]
    },
    token: getToken() || '',
    searchVisible: false,
    mobileMenuVisible: false,
    visitorAccess: 0,
    siteAccess: 0,
    isLoading: false,
    notice: null,
    isUnread: false
  },
  mutations: {
    setSiteInfo(state, info) {
      state.webSiteInfo = info
    },
    SET_TOKEN(state, token) {
      state.token = token
      setToken(token)
    },
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
      sessionStorage.setItem("user", JSON.stringify(userInfo))
    },
    SET_USER_ROLE(state, role) {
      if (state.userInfo) {
        state.userInfo.role = role
        sessionStorage.setItem("user", JSON.stringify(state.userInfo))
      }
    },

    SET_SEARCH_VISIBLE(state, visible) {
      state.searchVisible = visible
    },
    SET_MOBILE_MENU_VISIBLE(state, visible) {
      state.mobileMenuVisible = visible
    },
    setMobileMenuVisible(state, value) {
      state.mobileMenuVisible = value
    },
    setVisitorAccess(state, value) {
      state.visitorAccess = value
    },
    setSiteAccess(state, value) {
      state.siteAccess = value
    },
    SET_LOADING(state, status) {
      state.isLoading = status
    },
    SET_NOTICE(state, notice) {
      state.notice = notice
    }
  },
  actions: {
    
    /**
     * 设置公告信息
     */
    setNotice({ commit }, notice) {
      commit('SET_NOTICE', notice)
    },

    /**
     * 设置站点信息
     */
    setSiteInfo({ commit }, info) {
      commit('setSiteInfo', info)
    },
    /**
     * 获取用户信息
     */
    async getUserInfo({ commit }) {
      if(getToken()){
        const res = await getUserInfoApi()
        
        // 临时模拟会员数据，避免后端接口未实现导致的问题
        // 后端实现接口后删除此代码
        if (!res.data.memberInfo) {
          // 随机生成会员状态，30%概率是会员
          const isMember = Math.random() < 0.3;
          res.data.memberInfo = {
            isActive: isMember,
            level: isMember ? Math.floor(Math.random() * 3) + 1 : 0,
            expireTime: isMember ? '2025-12-31 23:59:59' : null,
            daysRemaining: isMember ? 180 : 0,
            daysPercentage: isMember ? 65 : 0
          };
        }
        
        // 添加会员信息标识
        if (res.data && res.data.memberInfo && res.data.memberInfo.isActive) {
          res.data.isMember = true
        } else {
          res.data.isMember = false
        }
        commit('SET_USER_INFO', res.data)
        
        // 获取用户角色信息
        try {
          const roleRes = await getUserRolesApi()
          // 检查是否包含超级管理员角色
          const isAdmin = roleRes.data && roleRes.data.some(role => 
            role.roleName === '超级管理员' || role.roleKey === 'admin'
          )
          commit('SET_USER_ROLE', isAdmin ? 'admin' : 'user')
        } catch (err) {
          console.error('获取用户角色失败:', err)
        }
      }
    },

    /**
     * 登录
     */
    async loginAction({ commit, dispatch }, loginData) {
      try {
        const res = await loginApi(loginData)
        if (res.data) {
          // 临时模拟会员数据，避免后端接口未实现导致的问题
          // 后端实现接口后删除此代码
          if (!res.data.memberInfo) {
            // 随机生成会员状态，30%概率是会员
            const isMember = Math.random() < 0.3;
            res.data.memberInfo = {
              isActive: isMember,
              level: isMember ? Math.floor(Math.random() * 3) + 1 : 0,
              expireTime: isMember ? '2025-12-31 23:59:59' : null,
              daysRemaining: isMember ? 180 : 0,
              daysPercentage: isMember ? 65 : 0
            };
          }
          
          // 添加会员信息标识
          if (res.data && res.data.memberInfo && res.data.memberInfo.isActive) {
            res.data.isMember = true
          } else {
            res.data.isMember = false
          }
          
          commit('SET_TOKEN', res.data.token)
          commit('SET_USER_INFO', res.data)
          
          // 获取用户角色信息
          try {
            const roleRes = await getUserRolesApi()
            // 检查是否包含超级管理员角色
            const isAdmin = roleRes.data && roleRes.data.some(role => 
              role.roleName === '超级管理员' || role.roleKey === 'admin'
            )
            commit('SET_USER_ROLE', isAdmin ? 'admin' : 'user')
          } catch (err) {
            console.error('获取用户角色失败:', err)
          }
          
          return Promise.resolve(res)
        }
       return Promise.reject(res)
      } catch (error) {
        return Promise.reject(error)
      }
    },

    /**
     * 退出登录
     */
    async logout({ commit }) {
      await logoutApi()
      removeToken()
      commit('SET_USER_INFO', null)
    },

    showLoading({ commit }) {
      commit('SET_LOADING', true)
    },

    hideLoading({ commit }) {
      commit('SET_LOADING', false)
    }
  }
})